package hk.linkcredit.walletservice.wallet.service.strategy;

import hk.linkcredit.walletservice.constant.Status;
import hk.linkcredit.walletservice.constant.WalletConstants;
import hk.linkcredit.walletservice.exception.BizException;
import hk.linkcredit.walletservice.wallet.domain.vo.WalletAccountInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Author: Jamnsin
 * @Date: 2022/6/12 16:26
 */
@Slf4j
@Component(WalletConstants.WALLET_TYPE_BALANCE)
public class WalletBalanceStrategy implements BalanceStrategy {

    @Override
    public void checkAmount(BigDecimal applyAmt, WalletAccountInfo walletAccount) {
        log.info("校验金额 [{}] >>> applyAmt = {}, walletAccount = {}", WalletConstants.WALLET_TYPE_BALANCE, applyAmt, walletAccount);

        // 获取客户钱包余额
        if (WalletConstants.WALLET_STATUS_LOCK.equals(walletAccount.getWalletStatus()) || WalletConstants.WALLET_STATUS_BALANCE_LOCK.equals(walletAccount.getWalletStatus())) {
            throw new BizException(Status.BALANCE_LOCK_CANNOT_WITHDRAW);
        }

        BigDecimal walletBalance = walletAccount.getBalance().compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : walletAccount.getBalance();
        BigDecimal frozenBalance = walletAccount.getFrozenBalance().compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : walletAccount.getFrozenBalance();
        BigDecimal minWithdrawBalance = walletAccount.getMinWithdrawBalance();
        BigDecimal serviceFee = walletBalance.multiply(walletAccount.getServiceRate());
        log.debug("余额及配置 >>> walletBalance = {}，frozenBalance = {}，minWithdrawBalance = {}", walletBalance, frozenBalance, minWithdrawBalance);

        if (applyAmt.compareTo(minWithdrawBalance) < 0) {
            throw new BizException(Status.WALLE_WITHDRAW_CANNOT_LOWER_MIN_BALANCE);
        }

        if (walletBalance.subtract(frozenBalance).compareTo(applyAmt) < 0) {
            throw new BizException(Status.WALLE_WITHDRAW_INSUFFICIENT_BALANCE);
        }
    }
}
